var express = require("express");
var router = express.Router();

// 引入moment
const moment = require("moment");
const AccountModel = require("../../models/AccountModel");

// 引入检测登录的中间件
const checkLoginMiddleware = require("../../middlewares/checkLoginMiddleware");

// 首页
router.get("/", function (req, res, next) {
  // 重定向到account页面
  res.redirect('/account')
});

// 记账本上的列表
router.get("/account", checkLoginMiddleware, function (req, res, next) {
  AccountModel.find()
    .sort({ time: -1 })
    .exec((err, data) => {
      if (err) {
        res.status(500).send("读取失败！");
        return;
      }
      res.render("list", { accounts: data, moment: moment }); // 这里居然把引入的库作为参数传到ejs中
    });
});

// 添加记录
router.get("/account/create", checkLoginMiddleware, function (req, res, next) {
  res.render("create");
});

// 新增记录
router.post("/account", checkLoginMiddleware, function (req, res, next) {
  const time = moment(req.body.time).toDate();
  AccountModel.create(
    {
      ...req.body,
      time,
    },
    (err, data) => {
      if (err) {
        res.status(500).send("添加失败！");
        return;
      }
      res.render("success", { msg: "添加成功~", url: "/account" });
    }
  );
});

// 删除记录
router.get("/account/:id", checkLoginMiddleware, function (req, res, next) {
  const id = req.params.id;
  AccountModel.deleteOne({ _id: id }, (err, data) => {
    if (err) {
      res.status(500).send("删除失败！");
      return;
    }
    res.render("success", { msg: "删除成功~", url: "/account" });
  });
});

module.exports = router;
